<template>
  <div class="container">
    <el-card style="max-width: 580px;margin: 30px auto;">
      <template #header>
        <div class="card-header">
          <span>基本资料</span>
        </div>
      </template>
      <el-form class="userForm" size="large" :rules="rules" :model="userInfo" ref="userRef" label-position="right"
        label-width="100">
        <el-form-item label="登录名称">
          <el-input style="font-size: 18px;" disabled :value="userInfo.username" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input style="font-size: 18px;" v-model="userInfo.nickname"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input style="font-size: 18px;" v-model="userInfo.email"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateUserInfo">提交修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<!-- 为啥得不到初始化数据original？？？ -->
<script setup>
import { userUpdateApi } from '@/api/user';
import { useUserStore } from '@/stores/useUserStore';
import { ElMessage } from 'element-plus';
import { storeToRefs } from 'pinia';
import { ref } from 'vue';

const userStore = useUserStore()
// 这样赋值是否合理
// const userInfo = userStore.userInfo
// console.log('userStore.userInfo:',userStore.userInfo)
// console.log('userInfo:',userInfo)

// const { userInfo } = toRef(userStore, 'userInfo')
const { userInfo } = storeToRefs(userStore)

// console.log("初始信息：",userStore.printUserInfo())

// console.log('userInfo:',userInfo.value)
// console.log('userInfo.username',userInfo.value.username)
const original = {
  nickname: userInfo.value.nickname,
  email: userInfo.value.email
}
console.log('original', original)

const rules = {
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入用户邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
}
const userRef = ref()
// TODO:为啥这里的original也是响应式的，因为这里的userInfo是响应式对象，所以这里赋值的其实是对象的地址
// const original = userInfo.value
// 修改
const updateUserInfo = async () => {
  await userRef.value.validate()
  const keys = Object.keys(original)//数组
  if (keys.every(key => original[key] === userInfo.value[key])) {
    ElMessage.error('至少修改一个属性')
    return
  }
  console.log('表单校验通过')
  await userUpdateApi(userInfo.value)
  ElMessage.success('修改信息成功')
  // console.log('userInfo:', userInfo)
  // console.log('original:', original)
  original.nickname = userInfo.value.nickname
  original.email = userInfo.value.email
  // TODO:为啥这样不行
  // original = {
  //   nickname:userInfo.value.nickname,
  //   email:userInfo.value.email
  // }
  // console.log('重新初始化original:',original)
}
</script>

<style scoped lang="scss"></style>